﻿using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using Framework.Exceptions.RepositoryExceptions;
using Interfaces.Criteria;
using Interfaces.Filters;
using Interfaces.Models;
using Interfaces.Providers;
using Interfaces.Repositories;
using Interfaces.RepositoryModels.InternalModels.EconomicInformationModels;

namespace SQLRepositories.EconomicRepositories
{
    public class QuoteisRepository : EntityBaseRepository<QuoteModel>, IQuoteisRepository, IEconomicDataProvider<IEnumerable<IQuote>, IQuoteisFilter, IKeySupportedCriteria>
    {
        public QuoteisRepository(IDBEconomicInformationServiceContext context) 
            : base(context)
        {}

        public void Create(QuoteModel item)
        {
            Context.Quoteis.Add(item);
            Context.SaveChanges();
        }

        public QuoteModel GetById(Guid id)
        {
            return Context.Quoteis.FirstOrDefault(x => x.Id.Equals(id));
        }

        public void Delete(Guid id)
        {
            var removeItem = Context.Quoteis.FirstOrDefault(x => x.Id.Equals(id));
            if(removeItem == null)
                throw new  EntityNotFoundException("Quote");
            Context.Quoteis.Remove(removeItem);
            Context.SaveChanges();
        }

        public void Delete(QuoteModel item)
        {
            Context.Quoteis.Remove(item);
            Context.SaveChanges();
        }

        public IEnumerable<QuoteModel> GetAll()
        {
            return Context.Quoteis;
        }

        public IEnumerable<IQuote> GetData(IKeySupportedCriteria criteria, IQuoteisFilter filter)
        {

            if (filter == null)
                throw new ArgumentNullException("filter");
            if (criteria == null)
                throw new ArgumentNullException("criteria");

            var source = from quote in Context.Quoteis 
                         where criteria.Identificators.Contains(quote.Symbol) 
                         select quote;
           
            RepositoryMappingHelper.ResetMapping();
            RepositoryMappingHelper.CreateQuoteMapping();

            var result = Mapper.Map<IEnumerable<QuoteModel>, IEnumerable<IQuote>>(source);
            return filter.Filtrate(result) as IEnumerable<IQuote>;
        }
    }
}
